package com.lqg.bookLibrary.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.exception.ServiceException;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.webService.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 注册接口
 * */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class RegisterController {
    @Autowired
    private RegisterService registerService;

    @Autowired
    private IUsersService usersService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    //获取验证码
    @GetMapping("/register/getCode/{email}")
    public JsonResult getCheckCode(@PathVariable String email){
        String msg;
        try {
            msg = registerService.getCheckCode(email);
        } catch (ServiceException e) {
            //e.printStackTrace();
            msg = e.getMessage();
            return JsonResult.error(msg);
        }
        if(msg.equals("验证码发送成功")){
            return JsonResult.success(msg,"success");
        }else {
            return JsonResult.error(msg);
        }
    }

    //提交验证
    @PostMapping("/register/verify")
//    public JsonResult verifyCheckCode(String email, String password, String checkCode){
    public JsonResult verifyCheckCode(@RequestBody String post){
        JSONObject keyValue = JSON.parseObject(post);
        String email = (String)keyValue.get("email");
        String username = (String)keyValue.get("username");
        String password=(String)keyValue.get("password");
        String checkCode=(String)keyValue.get("checkCode");
        System.out.println(username);
        String msg;
        try {
            msg = registerService.verifyCheckCode(username,email,password,checkCode);
            if(!msg.equals("验证码正确")){
                return JsonResult.error("注册失败",msg);
            }
        } catch (ServiceException e) {
            //e.printStackTrace();
            msg = e.getMessage();
            return JsonResult.error(msg);
        }

        boolean exists = usersService.lambdaQuery().eq(Users::getUsername, username).exists();
        if (exists) {
            return JsonResult.error("用户名已存在");
        }

        Users users = new Users();
        users.setUsername(username);
        users.setPassword(passwordEncoder.encode(password));
        users.setEmail(email);
        users.setPhoto("http://localhost:9001/book/user/default_avatar.png");
        users.setRole("c");
        boolean save = usersService.save(users);
        if (!save){
            return JsonResult.error("注册失败");
        }
        return JsonResult.success(msg,"success");
    }

}
